<?php
/**
 * 
 * @author Paolo Bertuzzo
 *
 */
namespace Catalog\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\Http\Header\RetryAfter;
use Zend\View\Model\ViewModel;
use Doctrine\ORM\EntityManager;
use Catalog\Service\ProductService;
use Utilities\Geolocation\GeolocationService;
use Catalog\Service\StoreService;
use Utilities\Session\SessionFacade;
use Zend\Paginator\Paginator;
use Catalog\Service\CategoryProductAdapter;

/**
 */
class CategoryController extends AbstractGeolocalizedController
{

    /**
     */
    protected $productService;

    /**
     */
    protected $itemsPerPage;
    
    /**
     * 
     * @param ProductService $productService
     * @param GeolocationService $geolocationService
     * @param StoreService $storeService
     * @param int itemsPerPage
     */
    public function __construct(ProductService $productService, GeolocationService $geolocationService, StoreService $storeService, $itemsPerPage)
    {
        parent::__construct($geolocationService, $storeService);
        
        $this->productService = $productService;
        $this->itemsPerPage = $itemsPerPage;
    }

    /**
     *
     * @return A view model describing the category's products
     *        
     */
    public function listAction()
    {
        $sessionFacade = new SessionFacade();
        
        // Get the request parameters
        $categoryAlias = $this->params()->fromRoute('category_alias');
        $page = $this->params()->fromRoute('page') ? (int) $this->params()->fromRoute('page') : 1;
        
        $store = parent::getStore();

        return new ViewModel(array(
            'locale' => $sessionFacade->getLocale(),
            'name' => $this->productService->getCategoryName($categoryAlias, $store->getLanguage()),
            'paginator' => $this->getPaginator($categoryAlias, $store->getLanguage(), $store->getId(), $page)
        ));
    }
    
    /**
     * 
     * @param string $categoryAlias
     * @param string $language
     * @param int $storeId
     * @param int $page
     * @return \Zend\Paginator\Paginator
     */
    private function getPaginator($categoryAlias, $language, $storeId, $page) 
    {
    	$paginator = new Paginator(new CategoryProductAdapter($this->productService, $categoryAlias, $language, $storeId));
    	
    	$paginator->setCurrentPageNumber($page)->setItemCountPerPage($this->itemsPerPage);
    	
    	return $paginator;
    }
    
}

?>